package com.lyh.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyh.common.core.domain.model.RegisterBodyTest;
import com.lyh.common.utils.DateUtils;
import com.lyh.system.mapper.SysUserMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lyh.common.constant.CacheConstants;
import com.lyh.common.constant.Constants;
import com.lyh.common.constant.UserConstants;
import com.lyh.common.core.domain.entity.SysUser;
import com.lyh.common.core.domain.model.RegisterBody;
import com.lyh.common.core.redis.RedisCache;
import com.lyh.common.exception.user.CaptchaException;
import com.lyh.common.exception.user.CaptchaExpireException;
import com.lyh.common.utils.MessageUtils;
import com.lyh.common.utils.SecurityUtils;
import com.lyh.common.utils.StringUtils;
import com.lyh.framework.manager.AsyncManager;
import com.lyh.framework.manager.factory.AsyncFactory;
import com.lyh.system.service.ISysConfigService;
import com.lyh.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.sql.Wrapper;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * 注册校验方法
 *
 * @author lyh
 */
@Component
@Transactional
public class SysRegisterService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody) {

        String uuid = registerBody.getUuid();
        if (uuid == null) {
            throw new RuntimeException("验证码错误！");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String code = redisCache.getCacheObject(verifyKey);
        if (code == null || !code.equals(registerBody.getCode())) {
            throw new RuntimeException("验证码错误！");
        }

        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setBirthday(DateUtils.parseDate("2001-01-01"));
        sysUser.setIsVip(0);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            // validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不能为空！");
        } else if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户密码不能为空！");
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new RuntimeException("账户长度必须在2到20个字符之间！");
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new RuntimeException("密码长度必须在5到20个字符之间！");
        } else if (!userService.checkUserNameUnique(sysUser)) {
            throw new RuntimeException("保存用户" + username + "失败，注册账号已存在");
        } else if (registerBody.getInvitationCode() == null) {
            throw new RuntimeException("邀请码不能为空！");
        } else {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setIsAdmin(0);
            sysUser.setCreateTime(new Date());
            sysUser.setPhonenumber(registerBody.getTelephone());
            QueryWrapper<SysUser> wrapper = new QueryWrapper();
            wrapper.eq("is_admin", 0);
            wrapper.orderByDesc("create_time");
            List<SysUser> sysUserList = sysUserMapper.selectList(wrapper);
            sysUserList.sort((o1, o2) -> {
                //按照code的大小升序排列
                if (Integer.parseInt(o1.getMemberId()) < Integer.parseInt(o2.getMemberId())) {
                    return 1;
                }
                if (Integer.parseInt(o1.getMemberId()) == Integer.parseInt(o2.getMemberId())) {
                    return 0;
                }
                return -1;
            });
            SysUser user1 = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getMemberId, (registerBody.getInvitationCode())));
            if (user1 == null) {
                throw new RuntimeException("邀请码所在用户不存在！");
            }
            //加锁
            String key = "register";
            RLock lock = redissonClient.getLock(key);

            try {
                if (lock.tryLock(30, 30, TimeUnit.SECONDS)) {
                    StringBuilder sb = new StringBuilder();
                    Integer i = Integer.parseInt(sysUserList.get(0).getMemberId()) + 1;
                    int length = 6 - i.toString().length();
                    for (int j = 0; j < length; j++) {
                        sb.append("0");
                    }
                    sysUser.setMemberId(sb.append(i).toString());
                }
            } catch (Exception ex) {
                throw new RuntimeException("注册失败，错误代码000001，请联系管理员！");
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
            if (isNotBlank(registerBody.getInvitationCode())) {
                try {
                    Long memberId = Long.valueOf(registerBody.getInvitationCode());
                    QueryWrapper<SysUser> wrapper1 = new QueryWrapper();
                    wrapper1.eq("member_id", memberId);
                    SysUser user = sysUserMapper.selectOne(wrapper1);
                    if (user != null) {
                        sysUser.setParentId(user.getUserId());
                        SysUser sysUser1 = sysUserMapper.selectById(user.getParentId());

                        if (sysUser1 != null) {
                            if (isNotBlank(sysUser1.getIndirectInviteCodes())) {
                                sysUser1.setIndirectInviteCodes(sysUser1.getIndirectInviteCodes() + "," + sysUser.getMemberId());
                            } else {
                                sysUser1.setIndirectInviteCodes(sysUser.getMemberId());
                            }
                            sysUserMapper.updateById(sysUser1);
                        }

                        List<SysUser> sysUsers = sysUserMapper.indirectUser(registerBody.getInvitationCode());
                        for (SysUser sysUser2 : sysUsers) {
                            sysUser2.setIndirectInviteCodes(sysUser2.getIndirectInviteCodes() + "," + sysUser.getMemberId());
                            sysUserMapper.updateById(sysUser2);
                        }

                    } else {
                        throw new RuntimeException("无效的邀请码！");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException("无效的邀请码！");
                }
            }
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    public SysUser testRegister(RegisterBodyTest registerBody) {

        /*String uuid = registerBody.getUuid();
        if (uuid == null) {
            throw new RuntimeException("验证码错误！");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String code = redisCache.getCacheObject(verifyKey);
        if (code == null || !code.equals(registerBody.getCode())) {
            throw new RuntimeException("验证码错误！");
        }*/

        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setBirthday(DateUtils.parseDate("2001-01-01"));

        if (isNotBlank(registerBody.getPayPassword())) {
            String encryptPassword = SecurityUtils.encryptPassword(registerBody.getPayPassword());
            sysUser.setPayPassword(encryptPassword);
        }

        if (registerBody.getIsVip() != null) {
            if (registerBody.getIsVip() == 1 || registerBody.getIsVip() == 3) {
                sysUser.setVipCommomTime(new Date());
            }
            if (registerBody.getIsVip() == 2 || registerBody.getIsVip() == 3) {
                sysUser.setVipStoreTime(new Date());
            }
            sysUser.setIsVip(registerBody.getIsVip());
        }
        if (registerBody.getMemberLevel() != null) {
            sysUser.setMemberLeve(registerBody.getMemberLevel());
        }

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            // validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不能为空！");
        } else if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户密码不能为空！");
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new RuntimeException("账户长度必须在2到20个字符之间！");
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new RuntimeException("密码长度必须在5到20个字符之间！");
        } else if (!userService.checkUserNameUnique(sysUser)) {
            throw new RuntimeException("保存用户" + username + "失败，注册账号已存在");
        } else if (registerBody.getInvitationCode() == null) {
            throw new RuntimeException("邀请码不能为空！");
        } else {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setIsAdmin(0);
            sysUser.setCreateTime(new Date());
            sysUser.setPhonenumber(registerBody.getTelephone());
            QueryWrapper<SysUser> wrapper = new QueryWrapper();
            wrapper.eq("is_admin", 0);
            wrapper.orderByDesc("create_time");
            List<SysUser> sysUserList = sysUserMapper.selectList(wrapper);
            sysUserList.sort((o1, o2) -> {
                //按照code的大小升序排列
                if (Integer.parseInt(o1.getMemberId()) < Integer.parseInt(o2.getMemberId())) {
                    return 1;
                }
                if (Integer.parseInt(o1.getMemberId()) == Integer.parseInt(o2.getMemberId())) {
                    return 0;
                }
                return -1;
            });
            SysUser user1 = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getMemberId, (registerBody.getInvitationCode())));
            if (user1 == null) {
                throw new RuntimeException("邀请码所在用户不存在！");
            }

            //加锁
            String key = "register";
            RLock lock = redissonClient.getLock(key);

            try {
                if (lock.tryLock(30, 30, TimeUnit.SECONDS)) {
                    StringBuilder sb = new StringBuilder();
                    Integer i = Integer.parseInt(sysUserList.get(0).getMemberId()) + 1;
                    int length = 6 - i.toString().length();
                    for (int j = 0; j < length; j++) {
                        sb.append("0");
                    }
                    sysUser.setMemberId(sb.append(i).toString());
                }
            } catch (Exception ex) {
                throw new RuntimeException("注册失败，错误代码000001，请联系管理员！");
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }

            if (isNotBlank(registerBody.getInvitationCode())) {
                try {
                    Long memberId = Long.valueOf(registerBody.getInvitationCode());
                    QueryWrapper<SysUser> wrapper1 = new QueryWrapper();
                    wrapper1.eq("member_id", memberId);
                    SysUser user = sysUserMapper.selectOne(wrapper1);
                    if (user != null) {
                        sysUser.setParentId(user.getUserId());
                        SysUser sysUser1 = sysUserMapper.selectById(user.getParentId());

                        if (sysUser1 != null) {
                            if (isNotBlank(sysUser1.getIndirectInviteCodes())) {
                                sysUser1.setIndirectInviteCodes(sysUser1.getIndirectInviteCodes() + "," + sysUser.getMemberId());
                            } else {
                                sysUser1.setIndirectInviteCodes(sysUser.getMemberId());
                            }
                            sysUserMapper.updateById(sysUser1);
                        }

                        List<SysUser> sysUsers = sysUserMapper.indirectUser(registerBody.getInvitationCode());
                        for (SysUser sysUser2 : sysUsers) {
                            sysUser2.setIndirectInviteCodes(sysUser2.getIndirectInviteCodes() + "," + sysUser.getMemberId());
                            sysUserMapper.updateById(sysUser2);
                        }

                    } else {
                        throw new RuntimeException("无效的邀请码！");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException("无效的邀请码！");
                }
            }
//            SysUser sysUser1 = userService.testRegister(sysUser);
/*            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }*/
        }
        return userService.testRegister(sysUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
}
